package top.hidoctor.auscultation.utils;

import android.os.Build;
import android.support.annotation.RequiresApi;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;

public class WavHeader {
    /**
     * RIFF数据块
     */
    final String riffChunkId = "RIFF";
    int riffChunkSize;
    final String riffType = "WAVE";

    /**
     * FORMAT 数据块
     */
    final String formatChunkId = "fmt ";
    final int formatChunkSize = 16;
    final short audioFormat = 1;
    short mChannels;
    int mSampleRate;
    int mByteRate;
    short mBlockAlign;
    short mSampleBits;

    /**
     * FORMAT 数据块
     */
    final String mDataChunkId = "data";
    int dataChunkSize;

    public WavHeader(int totalAudioLen, int sampleRate, short channels, short sampleBits) {
        this.riffChunkSize = totalAudioLen + 44 - 8;
        this.mChannels = channels;
        this.mSampleRate = sampleRate;
        this.mByteRate = sampleRate * sampleBits * channels / 8;
        this.mBlockAlign = (short) (channels * sampleBits / 8);
        this.mSampleBits = sampleBits;
        this.dataChunkSize = totalAudioLen;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public byte[] getHeader() {
        ByteBuffer buffer = ByteBuffer.allocate(44);
        buffer = buffer.order(ByteOrder.LITTLE_ENDIAN);
        buffer.put(riffChunkId.getBytes(StandardCharsets.UTF_8)); // The "RIFF" chunk descriptor
        buffer.putInt(riffChunkSize);  // ChunkSize 下个地址开始到文件尾的总字节数(此Chunk的数据大小)
        buffer.put(riffType.getBytes(StandardCharsets.UTF_8)); // "WAVE"
        buffer.put(formatChunkId.getBytes(StandardCharsets.UTF_8)); // "fmt + 空格"
        buffer.putInt(formatChunkSize); // SubChunkSize1 一般为16
        buffer.putShort(audioFormat); // 1：表示是PCM 编码
        buffer.putShort(mChannels); // 通道
        buffer.putInt(mSampleRate); // 采样率
        buffer.putInt(mByteRate); // 码率：采样率 * 采样位数 * 声道个数，bytePerSecond = sampleRate * (bitsPerSample / 8) * channels
        buffer.putShort(mBlockAlign); // 每次采样的大小：采样位数*声道数/8
        buffer.putShort(mSampleBits); // 采样位数
        buffer.put(mDataChunkId.getBytes(StandardCharsets.UTF_8)); // "data"
        buffer.putInt(dataChunkSize); // 音频数据长度
        buffer.flip();
        return buffer.array();
    }
}

